#include <iostream>
#include <cstdlib> 
#include <ctime>
#include <map>
#include <vector>
using namespace std;
string longestCommonPrefix(vector<string>& strs) {
    if (strs.empty()) return "";
    string res = strs[0];//取向量容器中的第一个字符串
    for (const string& s : strs)
    {
        for (int i = 0; i < res.size(); i++)
        {
            if (s[i] != res[i])
            {
                //substr用法： s.substr(i,j)表示从下标为i的位置开始截取j位。
                res = res.substr(0, i);
                break;
            }
        }
    }
    printf("公共前缀为：%s\n", res.c_str());
    return res;
}
string longestCommonPrefix2(vector<string>& strs) {
    if (strs.size() == 0)
    {
        printf("不存在公共前缀");
        return "";
    }
    char c;
    string res = strs[0];
    for (int i = 0; i < strs[0].size(); i++) {
        c = strs[0][i];
        for (int j = 1; j < strs.size(); j++) {
            if (i == strs[j].size() || c != strs[j][i])
            {   
                res = strs[0].substr(0, i);
                printf("公共前缀为：%s\n", res.c_str());
                return strs[0].substr(0, i);
            }
                
        }
    }
    return strs[0];
}


int main()
{
    vector<string> vec;//定义个一个字符串容器
    vec.push_back("abcdzhangsan");//把字符串"..."压进容器
    vec.push_back("abcdlisi");
    vec.push_back("abcde");
    printf("输入为：\n");
    for (int i = 0; i < vec.size(); i++) {
        cout << vec[i] << endl;//打印容器的内容
    }
    longestCommonPrefix(vec);
    vector<string> vec2;
    vec2.push_back("flzhangsan");
    vec2.push_back("fllisi");
    vec2.push_back("flwangwu");
    printf("输入为：\n");
    for (int i = 0; i < vec2.size(); i++) {
        cout << vec2[i] << endl;
    }
    longestCommonPrefix2(vec2);
    return 0;
}